<template>
  <div class="health-status-container">
    <div class="health-status-header">
      <h3>
        <el-icon><Monitor /></el-icon>
        系统健康状态
      </h3>
      <el-button 
        type="primary" 
        size="small" 
        :loading="checking" 
        @click="checkAllHealth"
      >
        <el-icon><Refresh /></el-icon>
        刷新状态
      </el-button>
    </div>

    <div class="health-items">
      <!-- DeepSeek AI服务状态 -->
      <div class="health-item" :class="getStatusClass(deepSeekStatus)">
        <div class="health-item-header">
          <el-icon><Monitor /></el-icon>
          <span>DeepSeek AI服务</span>
          <el-tag :type="getTagType(deepSeekStatus)" size="small">
            {{ getStatusText(deepSeekStatus) }}
          </el-tag>
        </div>
        <div class="health-item-details" v-if="deepSeekDetails">
          <p>{{ deepSeekDetails }}</p>
        </div>
        <div class="health-item-time" v-if="deepSeekLastCheck">
          最后检查: {{ formatTime(deepSeekLastCheck) }}
        </div>
      </div>

      <!-- API密钥配置状态 -->
      <div class="health-item" :class="getStatusClass(apiKeyStatus)">
        <div class="health-item-header">
          <el-icon><Key /></el-icon>
          <span>API密钥配置</span>
          <el-tag :type="getTagType(apiKeyStatus)" size="small">
            {{ getStatusText(apiKeyStatus) }}
          </el-tag>
        </div>
        <div class="health-item-details" v-if="apiKeyDetails">
          <p>{{ apiKeyDetails }}</p>
        </div>
        <div class="health-item-time" v-if="apiKeyLastCheck">
          最后检查: {{ formatTime(apiKeyLastCheck) }}
        </div>
      </div>

      <!-- 系统整体状态 -->
      <div class="health-item" :class="getStatusClass(systemStatus)">
        <div class="health-item-header">
          <el-icon><Setting /></el-icon>
          <span>系统整体状态</span>
          <el-tag :type="getTagType(systemStatus)" size="small">
            {{ getStatusText(systemStatus) }}
          </el-tag>
        </div>
        <div class="health-item-details" v-if="systemDetails">
          <p>{{ systemDetails }}</p>
        </div>
        <div class="health-item-time" v-if="systemLastCheck">
          最后检查: {{ formatTime(systemLastCheck) }}
        </div>
      </div>

      <!-- AI聊天功能测试 -->
      <div class="health-item" :class="getStatusClass(chatTestStatus)">
        <div class="health-item-header">
          <el-icon><ChatDotRound /></el-icon>
          <span>AI聊天功能</span>
          <el-tag :type="getTagType(chatTestStatus)" size="small">
            {{ getStatusText(chatTestStatus) }}
          </el-tag>
        </div>
        <div class="health-item-details" v-if="chatTestDetails">
          <p>{{ chatTestDetails }}</p>
        </div>
        <div class="health-item-time" v-if="chatTestLastCheck">
          最后检查: {{ formatTime(chatTestLastCheck) }}
        </div>
      </div>
    </div>

    <!-- 整体健康评分 -->
    <div class="health-summary">
      <div class="health-score">
        <span class="score-label">整体健康评分:</span>
        <span class="score-value" :class="getScoreClass(overallScore)">{{ overallScore }}%</span>
      </div>
      <div class="health-recommendation" v-if="recommendation">
        <el-icon><InfoFilled /></el-icon>
        <span>{{ recommendation }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Monitor, Refresh, Key, Setting, ChatDotRound, InfoFilled } from '@element-plus/icons-vue'
import { healthCheckApi } from '@/api/healthCheck'

// 健康状态数据
const checking = ref(false)
const deepSeekStatus = ref('unknown')
const deepSeekDetails = ref('')
const deepSeekLastCheck = ref(null)

const apiKeyStatus = ref('unknown')
const apiKeyDetails = ref('')
const apiKeyLastCheck = ref(null)

const systemStatus = ref('unknown')
const systemDetails = ref('')
const systemLastCheck = ref(null)

const chatTestStatus = ref('unknown')
const chatTestDetails = ref('')
const chatTestLastCheck = ref(null)

// 计算整体健康评分
const overallScore = computed(() => {
  const statuses = [deepSeekStatus.value, apiKeyStatus.value, systemStatus.value, chatTestStatus.value]
  const healthyCount = statuses.filter(status => status === 'healthy').length
  const totalCount = statuses.filter(status => status !== 'unknown').length
  
  if (totalCount === 0) return 0
  return Math.round((healthyCount / totalCount) * 100)
})

// 计算推荐信息
const recommendation = computed(() => {
  const score = overallScore.value
  if (score >= 90) return '系统运行良好，所有服务正常'
  if (score >= 70) return '系统基本正常，建议关注部分服务状态'
  if (score >= 50) return '系统存在问题，建议检查配置和服务状态'
  return '系统存在严重问题，请立即检查和修复'
})

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 'healthy': return 'status-healthy'
    case 'unhealthy': return 'status-unhealthy'
    case 'warning': return 'status-warning'
    default: return 'status-unknown'
  }
}

// 获取标签类型
const getTagType = (status) => {
  switch (status) {
    case 'healthy': return 'success'
    case 'unhealthy': return 'danger'
    case 'warning': return 'warning'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'healthy': return '正常'
    case 'unhealthy': return '异常'
    case 'warning': return '警告'
    default: return '未知'
  }
}

// 获取评分样式类
const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 70) return 'score-good'
  if (score >= 50) return 'score-warning'
  return 'score-poor'
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 检查DeepSeek健康状态
const checkDeepSeekHealth = async () => {
  try {
    const response = await healthCheckApi.checkDeepSeekHealth()
    deepSeekStatus.value = response.data?.status || 'healthy'
    deepSeekDetails.value = response.data?.message || '服务正常运行'
    deepSeekLastCheck.value = Date.now()
  } catch (error) {
    deepSeekStatus.value = 'unhealthy'
    deepSeekDetails.value = error.message || 'DeepSeek服务检查失败'
    deepSeekLastCheck.value = Date.now()
  }
}

// 检查API密钥状态
const checkApiKeyStatus = async () => {
  try {
    const response = await healthCheckApi.checkApiKeyStatus()
    apiKeyStatus.value = response.data?.status || 'healthy'
    apiKeyDetails.value = response.data?.message || 'API密钥配置正常'
    apiKeyLastCheck.value = Date.now()
  } catch (error) {
    apiKeyStatus.value = 'unhealthy'
    apiKeyDetails.value = error.message || 'API密钥配置检查失败'
    apiKeyLastCheck.value = Date.now()
  }
}

// 检查系统健康状态
const checkSystemHealth = async () => {
  try {
    const response = await healthCheckApi.checkSystemHealth()
    systemStatus.value = response.data?.status || 'healthy'
    systemDetails.value = response.data?.message || '系统运行正常'
    systemLastCheck.value = Date.now()
  } catch (error) {
    systemStatus.value = 'unhealthy'
    systemDetails.value = error.message || '系统健康检查失败'
    systemLastCheck.value = Date.now()
  }
}

// 测试AI聊天功能
const testAiChat = async () => {
  try {
    const response = await healthCheckApi.testAiChat('系统健康检查测试')
    if (response.data && typeof response.data === 'string' && response.data.length > 0) {
      chatTestStatus.value = 'healthy'
      chatTestDetails.value = 'AI聊天功能正常，响应正常'
    } else {
      chatTestStatus.value = 'warning'
      chatTestDetails.value = 'AI聊天功能响应异常'
    }
    chatTestLastCheck.value = Date.now()
  } catch (error) {
    chatTestStatus.value = 'unhealthy'
    chatTestDetails.value = error.message || 'AI聊天功能测试失败'
    chatTestLastCheck.value = Date.now()
  }
}

// 检查所有健康状态
const checkAllHealth = async () => {
  checking.value = true
  try {
    await Promise.allSettled([
      checkDeepSeekHealth(),
      checkApiKeyStatus(),
      checkSystemHealth(),
      testAiChat()
    ])
    ElMessage.success('健康检查完成')
  } catch (error) {
    ElMessage.error('健康检查过程中出现错误')
  } finally {
    checking.value = false
  }
}

// 组件挂载时自动检查
onMounted(() => {
  checkAllHealth()
})
</script>

<style scoped>
.health-status-container {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.health-status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.health-status-header h3 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
}

.health-items {
  display: grid;
  gap: 15px;
  margin-bottom: 20px;
}

.health-item {
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.health-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.health-item.status-healthy {
  border-color: #67c23a;
  background-color: #f0f9ff;
}

.health-item.status-unhealthy {
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.health-item.status-warning {
  border-color: #e6a23c;
  background-color: #fdf6ec;
}

.health-item.status-unknown {
  border-color: #909399;
  background-color: #f4f4f5;
}

.health-item-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.health-item-header span {
  flex: 1;
  font-weight: 500;
  color: #2c3e50;
}

.health-item-details {
  margin: 8px 0;
  padding: 8px 12px;
  background-color: rgba(0, 0, 0, 0.02);
  border-radius: 4px;
  font-size: 14px;
  color: #666;
}

.health-item-time {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.health-summary {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
  text-align: center;
}

.health-score {
  margin-bottom: 15px;
}

.score-label {
  font-size: 16px;
  margin-right: 10px;
}

.score-value {
  font-size: 24px;
  font-weight: bold;
}

.score-excellent {
  color: #67c23a;
}

.score-good {
  color: #409eff;
}

.score-warning {
  color: #e6a23c;
}

.score-poor {
  color: #f56c6c;
}

.health-recommendation {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
  opacity: 0.9;
}

@media (max-width: 768px) {
  .health-status-container {
    padding: 15px;
  }
  
  .health-status-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .health-item-header {
    flex-wrap: wrap;
  }
}
</style>